/**
 * 安全评估证明材料收集系统状态管理
 * 简化版本：移除 dispatch 模式，直接暴露函数
 */

import React, { createContext, useContext, useState, useMemo, type ReactNode } from 'react';
import type {
  EvaluationItem,
  UploadedFile,
  AIAnalysisResult,
  AIAdjustmentCommand,
  Statistics,
  ExportConfig,
  SortConfig,
  FilterConfig
} from '@/types/ProofMapper';
import type { VersionMeta, VersionSnapshot, SharedResponse, SnapshotCreate } from '@/types/ProofMapper';
import { proofMapperAPI } from '@/api/proofMapper';
import { showMessage } from '@/components/common/MessageTip';

// 初始状态
const initialState = {
  // 文件上传相关
  uploadedFiles: [] as UploadedFile[],
  currentFile: null as UploadedFile | null,
  
  // 评估项相关
  evaluationItems: [] as EvaluationItem[],
  selectedItems: [] as string[],
  
  // AI 相关
  analysisResult: null as AIAnalysisResult | null,
  adjustmentCommands: [] as AIAdjustmentCommand[],
  aiInputValue: '',
  
  // 表格相关
  sortConfig: {
    field: 'module',
    direction: 'desc' as 'asc' | 'desc'
  } as SortConfig,
  filterConfig: {} as FilterConfig,
  
  // 导出相关
  exportConfig: {
    format: 'word',
    include_notes: true,
    include_summary: true,
    selected_items_only: false
  } as ExportConfig,
  
  // 统计信息
  statistics: {
    total_items: 0,
    modules_count: 0,
    important_items: 0,
    exported_items: 0
  } as Statistics,
  
  // UI 状态
  loading: false,
  error: null as string | null,

  // 版本相关
  isVersionSaved: false,
  lastSavedVersionName: undefined as string | undefined,
  versionList: [] as VersionMeta[],  // 版本列表（替代单个 versionMeta）
  loadingVersions: false,
  currentSnapshotId: null as string | null  // 当前加载的快照ID
};

type ProofMapperState = typeof initialState;

// Context 类型 - 简化版本，移除 dispatch
interface ProofMapperContextType {
  // 状态暴露
  uploadedFiles: UploadedFile[];
  currentFile: UploadedFile | null;
  evaluationItems: EvaluationItem[];
  selectedItems: string[];
  analysisResult: AIAnalysisResult | null;
  adjustmentCommands: AIAdjustmentCommand[];
  aiInputValue: string;
  sortConfig: SortConfig;
  filterConfig: FilterConfig;
  exportConfig: ExportConfig;
  statistics: Statistics;
  loading: boolean;
  error: string | null;
  isVersionSaved: boolean;
  lastSavedVersionName: string | undefined;
  versionList: VersionMeta[];
  loadingVersions: boolean;
  currentSnapshotId: string | null;
  
  // 文件管理函数
  addFile: (file: UploadedFile) => void;
  deleteFile: (id: string) => void;
  updateFileStatus: (id: string, status: UploadedFile['status'], progress?: number) => void;
  
  // 评估项管理函数
  setEvaluationItems: (items: EvaluationItem[]) => void;
  updateEvaluationItem: (item: EvaluationItem) => void;
  deleteEvaluationItem: (id: string) => void;
  addEvaluationItem: (item: EvaluationItem) => void;
  toggleItemSelection: (id: string) => void;
  setSelectedItems: (ids: string[]) => void;
  selectAllItems: () => void;
  clearSelection: () => void;
  
  // AI 相关函数
  setAnalysisResult: (result: AIAnalysisResult) => void;
  addAdjustmentCommand: (command: AIAdjustmentCommand) => void;
  updateAdjustmentCommand: (id: string, updates: Partial<AIAdjustmentCommand>) => void;
  setAiInput: (value: string) => void;
  
  // 配置管理函数
  setSortConfig: (config: SortConfig) => void;
  setFilterConfig: (config: FilterConfig) => void;
  setExportConfig: (config: ExportConfig) => void;
  updateStatistics: (stats: Statistics) => void;
  setLoading: (loading: boolean) => void;
  setError: (error: string | null) => void;
  
  // 版本管理函数
  loadVersionList: (assessmentType: string) => Promise<void>;
  loadVersionById: (assessmentType: string, snapshotId: string) => Promise<VersionSnapshot | null>;
  applySnapshot: (snapshot: VersionSnapshot) => void;
  createVersion: (assessmentType: string, name: string) => Promise<boolean>;
  updateVersion: (snapshotId: string, name: string) => Promise<boolean>;
  deleteVersion: (snapshotId: string) => Promise<boolean>;
  
  // API 调用函数
  parsePdf: (file: File) => Promise<boolean>;
  applyUserInput: (input: string) => Promise<boolean>;
  rollback: () => Promise<boolean>;
  loadHistory: () => Promise<{ modification_log: any[]; summary: any } | null>;
  saveSnapshot: (name: string, assessmentType: string) => Promise<boolean>;
  
  // 计算属性
  filteredItems: EvaluationItem[];
  sortedItems: EvaluationItem[];
  selectedItemsCount: number;
  hasSelectedItems: boolean;
  
  // 会话状态
  sharedId: string | null;
  shared: SharedResponse | null;
  history: any[];
  historySummary: any | null;
}

// 创建 Context
const ProofMapperContext = createContext<ProofMapperContextType | undefined>(undefined);

// Provider 组件
export const ProofMapperProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
  // 主状态管理
  const [state, setState] = useState<ProofMapperState>(initialState);
  
  // 会话状态（与主状态解耦）
  const [sharedId, setSharedId] = useState<string | null>(null);
  const [shared, setShared] = useState<SharedResponse | null>(null);
  const [history, setHistory] = useState<any[]>([]);
  const [historySummary, setHistorySummary] = useState<any | null>(null);

  // ===== 文件管理函数 =====
  
  /** 添加文件 */
  const addFile = (file: UploadedFile) => {
    setState(prev => ({
      ...prev,
      uploadedFiles: [...prev.uploadedFiles, file],
      currentFile: file
    }));
  };

  /** 删除文件 */
  const deleteFile = (id: string) => {
    setState(prev => ({
      ...prev,
      uploadedFiles: prev.uploadedFiles.filter(file => file.id !== id),
      currentFile: prev.currentFile?.id === id ? null : prev.currentFile
    }));
  };

  /** 更新文件状态 */
  const updateFileStatus = (id: string, status: UploadedFile['status'], progress?: number) => {
    setState(prev => ({
      ...prev,
      uploadedFiles: prev.uploadedFiles.map(file =>
        file.id === id
          ? {
              ...file,
              status,
              progress
            }
          : file
      ),
      currentFile: prev.currentFile?.id === id
        ? {
            ...prev.currentFile,
            status,
            progress
          }
        : prev.currentFile
    }));
  };

  // ===== 评估项管理函数 =====

  /** 设置评估项列表 */
  const setEvaluationItems = (items: EvaluationItem[]) => {
    const modules = new Set(items.map(item => item.module));
    setState(prev => ({
      ...prev,
      evaluationItems: items,
      statistics: {
        ...prev.statistics,
        total_items: items.length,
        modules_count: modules.size
      },
      isVersionSaved: false
    }));
  };

  /** 更新单个评估项 */
  const updateEvaluationItem = (item: EvaluationItem) => {
    setState(prev => ({
      ...prev,
      evaluationItems: prev.evaluationItems.map(existingItem =>
        existingItem.id === item.id ? item : existingItem
      ),
      isVersionSaved: false
    }));
  };

  /** 删除评估项 */
  const deleteEvaluationItem = (id: string) => {
    setState(prev => {
      const filteredItems = prev.evaluationItems.filter(item => item.id !== id);
      const remainingModules = new Set(filteredItems.map(item => item.module));
      
      return {
        ...prev,
        evaluationItems: filteredItems,
        selectedItems: prev.selectedItems.filter(selectedId => selectedId !== id),
        statistics: {
          ...prev.statistics,
          total_items: filteredItems.length,
          modules_count: remainingModules.size
        },
        isVersionSaved: false
      };
    });
  };

  /** 添加评估项 */
  const addEvaluationItem = (item: EvaluationItem) => {
    setState(prev => {
      const allItems = [...prev.evaluationItems, item];
      const allModules = new Set(allItems.map(item => item.module));
      
      return {
        ...prev,
        evaluationItems: allItems,
        statistics: {
          ...prev.statistics,
          total_items: allItems.length,
          modules_count: allModules.size
        },
        isVersionSaved: false
      };
    });
  };

  /** 切换项选择状态 */
  const toggleItemSelection = (id: string) => {
    setState(prev => {
      const isSelected = prev.selectedItems.includes(id);
      const newSelectedItems = isSelected
        ? prev.selectedItems.filter(selectedId => selectedId !== id)
        : [...prev.selectedItems, id];
      
      return {
        ...prev,
        selectedItems: newSelectedItems
      };
    });
  };

  /** 设置选中项 */
  const setSelectedItems = (ids: string[]) => {
    setState(prev => ({
      ...prev,
      selectedItems: ids
    }));
  };

  /** 全选 */
  const selectAllItems = () => {
    const allIds = state.evaluationItems.map(item => item.id);
    setSelectedItems(allIds);
  };

  /** 清空选择 */
  const clearSelection = () => {
    setSelectedItems([]);
  };

  // ===== AI 相关函数 =====

  /** 设置分析结果 */
  const setAnalysisResult = (result: AIAnalysisResult) => {
    setState(prev => ({
      ...prev,
      analysisResult: result
    }));
  };

  /** 添加调整命令 */
  const addAdjustmentCommand = (command: AIAdjustmentCommand) => {
    setState(prev => {
      // 如果命令已执行，替换未执行的版本
      if (command.executed) {
        const index = prev.adjustmentCommands.findIndex(
          cmd => cmd.id === command.id && !cmd.executed
        );
        if (index !== -1) {
          return {
            ...prev,
            adjustmentCommands: [
              ...prev.adjustmentCommands.slice(0, index),
              command,
              ...prev.adjustmentCommands.slice(index + 1)
            ]
          };
        }
      }
      
      return {
        ...prev,
        adjustmentCommands: [...prev.adjustmentCommands, command]
      };
    });
  };

  /** 更新调整命令 */
  const updateAdjustmentCommand = (id: string, updates: Partial<AIAdjustmentCommand>) => {
    setState(prev => ({
      ...prev,
      adjustmentCommands: prev.adjustmentCommands.map(cmd =>
        cmd.id === id ? { ...cmd, ...updates } : cmd
      )
    }));
  };

  /** 设置AI输入值 */
  const setAiInput = (value: string) => {
    setState(prev => ({
      ...prev,
      aiInputValue: value
    }));
  };

  // ===== 配置管理函数 =====

  /** 设置排序配置 */
  const setSortConfig = (config: SortConfig) => {
    setState(prev => ({
      ...prev,
      sortConfig: config
    }));
  };

  /** 设置过滤配置 */
  const setFilterConfig = (config: FilterConfig) => {
    setState(prev => ({
      ...prev,
      filterConfig: config
    }));
  };

  /** 设置导出配置 */
  const setExportConfig = (config: ExportConfig) => {
    setState(prev => ({
      ...prev,
      exportConfig: config
    }));
  };

  /** 更新统计信息 */
  const updateStatistics = (stats: Statistics) => {
    setState(prev => ({
      ...prev,
      statistics: stats
    }));
  };

  /** 设置加载状态 */
  const setLoading = (loading: boolean) => {
    setState(prev => ({
      ...prev,
      loading
    }));
  };

  /** 设置错误信息 */
  const setError = (error: string | null) => {
    setState(prev => ({
      ...prev,
      error
    }));
  };

  // ===== 版本管理函数 =====

  /** 加载版本列表 */
  const loadVersionList = async (assessmentType: string) => {
    setState(prev => ({ ...prev, loadingVersions: true }));
    try {
      const result = await proofMapperAPI.getSnapshots(assessmentType);
      setState(prev => ({ 
        ...prev, 
        versionList: result.snapshots.map(s => ({
          id: s.id,
          name: s.name,
          saved_at: s.saved_at,
          items_count: s.evaluation_items.length,
          modules_count: new Set(s.evaluation_items.map(i => i.module)).size
        })),
        loadingVersions: false
      }));
    } catch (e) {
      console.error('Load version list error:', e);
      setState(prev => ({ ...prev, loadingVersions: false, versionList: [] }));
    }
  };

  /** 根据ID加载版本 */
  const loadVersionById = async (assessmentType: string, snapshotId: string): Promise<VersionSnapshot | null> => {
    try {
      const res = await proofMapperAPI.getSnapshotById(assessmentType, snapshotId);
      if (res.shared_id) setSharedId(res.shared_id);
      
      const snapshot: VersionSnapshot = {
        meta: {
          id: res.id,
          name: res.name,
          saved_at: res.saved_at,
          items_count: res.evaluation_items.length,
          modules_count: new Set(res.evaluation_items.map(i => i.module)).size
        },
        evaluationItems: res.evaluation_items as unknown as EvaluationItem[],
        exportConfig: state.exportConfig,
        statistics: state.statistics
      };
      
      setState(prev => ({ ...prev, currentSnapshotId: snapshotId }));
      return snapshot;
    } catch (e: any) {
      showMessage('error', `加载版本失败: ${e?.message || '网络错误'}`);
      return null;
    }
  };

  /** 应用快照 */
  const applySnapshot = (snapshot: VersionSnapshot) => {
    setState(prev => ({
      ...prev,
      evaluationItems: snapshot.evaluationItems,
      statistics: snapshot.statistics,
      exportConfig: snapshot.exportConfig,
      uploadedFiles: [],
      currentFile: null,
      selectedItems: [],
      isVersionSaved: true,
      lastSavedVersionName: snapshot.meta?.name
    }));
  };

  /** 创建新版本 */
  const createVersion = async (assessmentType: string, name: string): Promise<boolean> => {
    try {
      const payload: SnapshotCreate = {
        assessment_type: assessmentType,
        name: name.trim(),
        evaluation_items: state.evaluationItems.map(item => ({
          id: item.id,
          module: item.module,
          category: item.category,
          checkpoint: item.checkpoint,
          materials: item.materials,
          notes: item.notes,
          selected: item.selected,
          updated_at: item.updated_at
        }))
      };
      
      const response = await proofMapperAPI.createSnapshot(payload);
      
      // 刷新版本列表
      await loadVersionList(assessmentType);
      
      setState(prev => ({ 
        ...prev, 
        currentSnapshotId: response.id,
        isVersionSaved: true,
        lastSavedVersionName: name.trim()
      }));
      
      showMessage('success', '版本已保存');
      return true;
    } catch (e: any) {
      console.error('Create version error:', e);
      showMessage('error', `保存版本失败: ${e?.message || '网络错误'}`);
      return false;
    }
  };

  /** 更新版本 */
  const updateVersion = async (snapshotId: string, name: string): Promise<boolean> => {
    try {
      const payload = {
        name: name.trim(),
        evaluation_items: state.evaluationItems.map(item => ({
          id: item.id,
          module: item.module,
          category: item.category,
          checkpoint: item.checkpoint,
          materials: item.materials,
          notes: item.notes,
          selected: item.selected,
          updated_at: item.updated_at
        }))
      };
      
      await proofMapperAPI.updateSnapshot(snapshotId, payload);
      showMessage('success', '版本已更新');
      return true;
    } catch (e: any) {
      console.error('Update version error:', e);
      showMessage('error', `更新版本失败: ${e?.message || '网络错误'}`);
      return false;
    }
  };

  /** 删除版本 */
  const deleteVersion = async (snapshotId: string): Promise<boolean> => {
    try {
      await proofMapperAPI.deleteSnapshot(snapshotId);
      
      // 从状态中移除
      setState(prev => ({
        ...prev,
        versionList: prev.versionList.filter(v => v.id !== snapshotId)
      }));
      
      showMessage('success', '版本已删除');
      return true;
    } catch (e: any) {
      console.error('Delete version error:', e);
      showMessage('error', `删除版本失败: ${e?.message || '网络错误'}`);
      return false;
    }
  };

  // ===== API 调用函数 =====

  /** 解析 PDF 文件 */
  const parsePdf = async (file: File): Promise<boolean> => {
    try {
      setLoading(true);
      const response = await proofMapperAPI.parsePdf(file);
      setSharedId(response.shared_id);
      setShared(response);
      setEvaluationItems(response.final_output.items as unknown as EvaluationItem[]);
      return true;
    } catch (e: any) {
      setError(e?.message || '解析 PDF 失败');
      return false;
    } finally {
      setLoading(false);
    }
  };


  /** 应用自然语言修改 */
  const applyUserInput = async (input: string): Promise<boolean> => {
    if (!sharedId) return false;
    try {
      setLoading(true);
      const res = await proofMapperAPI.applyUserInput(sharedId, input);
      setShared(res);
      setEvaluationItems(res.final_output.items as unknown as EvaluationItem[]);
      return true;
    } catch (e: any) {
      showMessage('error', `应用指令失败: ${e?.message || '网络错误'}`);
      setError(e?.message || '应用指令失败');
      return false;
    } finally {
      setLoading(false);
    }
  };

  /** 回滚最近一次修改 */
  const rollback = async (): Promise<boolean> => {
    if (!sharedId) return false;
    try {
      setLoading(true);
      const res = await proofMapperAPI.rollback(sharedId);
      setShared(res);
      setEvaluationItems(res.final_output.items as unknown as EvaluationItem[]);
      return true;
    } catch (e: any) {
      setError(e?.message || '回滚失败');
      return false;
    } finally {
      setLoading(false);
    }
  };

  /** 加载历史摘要 */
  const loadHistory = async (): Promise<{ modification_log: any[]; summary: any } | null> => {
    if (!sharedId) return null;
    try {
      const res = await proofMapperAPI.getHistory(sharedId);
      setHistory(res.modification_log || []);
      setHistorySummary(res.summary || null);
      return res;
    } catch (e) {
      return null;
    }
  };

  /** 保存当前为后端快照 */
  const saveSnapshot = async (name: string, assessmentType: string): Promise<boolean> => {
    try {
      const payload: SnapshotCreate = {
        assessment_type: assessmentType,
        name: name.trim(),
        evaluation_items: state.evaluationItems as unknown as any[],
      };
      await proofMapperAPI.createSnapshot(payload);
      return true;
    } catch (e: any) {
      setError(e?.message || '保存快照失败');
      return false;
    }
  };

  // ===== 计算属性 =====

  /** 过滤后的评估项 */
  const filteredItems = useMemo(() => {
    let items = state.evaluationItems;
    
    // 按模块过滤
    if (state.filterConfig.module) {
      items = items.filter(item => item.module === state.filterConfig.module);
    }
    
    // 按类别过滤
    if (state.filterConfig.category) {
      items = items.filter(item => item.category === state.filterConfig.category);
    }
    
    // 按选中状态过滤
    if (state.filterConfig.selected_only) {
      items = items.filter(item => item.selected);
    }
    
    // 按搜索词过滤
    if (state.filterConfig.search_term) {
      const searchTerm = state.filterConfig.search_term.toLowerCase();
      items = items.filter(item =>
        item.module.toLowerCase().includes(searchTerm) ||
        item.checkpoint.toLowerCase().includes(searchTerm) ||
        item.materials.some(material => material.toLowerCase().includes(searchTerm)) ||
        item.notes.toLowerCase().includes(searchTerm)
      );
    }
    
    return items;
  }, [state.evaluationItems, state.filterConfig]);

  /** 排序后的评估项 */
  const sortedItems = useMemo(() => {
    const items = [...filteredItems];
    const { field, direction } = state.sortConfig;
    
    items.sort((a, b) => {
      let aValue: any = a[field];
      let bValue: any = b[field];
      
      // 处理undefined值
      if (aValue === undefined && bValue === undefined) return 0;
      if (aValue === undefined) return direction === 'asc' ? 1 : -1;
      if (bValue === undefined) return direction === 'asc' ? -1 : 1;
      
      // 处理字符串比较
      if (typeof aValue === 'string' && typeof bValue === 'string') {
        aValue = aValue.toLowerCase();
        bValue = bValue.toLowerCase();
      }
      
      if (aValue < bValue) return direction === 'asc' ? -1 : 1;
      if (aValue > bValue) return direction === 'asc' ? 1 : -1;
      return 0;
    });
    
    return items;
  }, [filteredItems, state.sortConfig]);

  const selectedItemsCount = state.selectedItems.length;
  const hasSelectedItems = selectedItemsCount > 0;

  // ===== Context Value =====

  const contextValue: ProofMapperContextType = useMemo(() => ({
    // 状态暴露
    ...state,
    
    // 文件管理函数
    addFile,
    deleteFile,
    updateFileStatus,
    
    // 评估项管理函数
    setEvaluationItems,
    updateEvaluationItem,
    deleteEvaluationItem,
    addEvaluationItem,
    toggleItemSelection,
    setSelectedItems,
    selectAllItems,
    clearSelection,
    
    // AI 相关函数
    setAnalysisResult,
    addAdjustmentCommand,
    updateAdjustmentCommand,
    setAiInput,
    
    // 配置管理函数
    setSortConfig,
    setFilterConfig,
    setExportConfig,
    updateStatistics,
    setLoading,
    setError,
    
    // 版本管理函数
    loadVersionList,
    loadVersionById,
    applySnapshot,
    createVersion,
    updateVersion,
    deleteVersion,
    
    // API 调用函数
    parsePdf,
    applyUserInput,
    rollback,
    loadHistory,
    saveSnapshot,
    
    // 计算属性
    filteredItems,
    sortedItems,
    selectedItemsCount,
    hasSelectedItems,
    
    // 会话状态
    sharedId,
    shared,
    history,
    historySummary
  }), [
    state,
    addFile,
    deleteFile,
    updateFileStatus,
    setEvaluationItems,
    updateEvaluationItem,
    deleteEvaluationItem,
    addEvaluationItem,
    toggleItemSelection,
    setSelectedItems,
    selectAllItems,
    clearSelection,
    setAnalysisResult,
    addAdjustmentCommand,
    setAiInput,
    setSortConfig,
    setFilterConfig,
    setExportConfig,
    updateStatistics,
    setLoading,
    setError,
    loadVersionList,
    loadVersionById,
    applySnapshot,
    createVersion,
    updateVersion,
    deleteVersion,
    parsePdf,
    applyUserInput,
    rollback,
    loadHistory,
    saveSnapshot,
    filteredItems,
    sortedItems,
    selectedItemsCount,
    hasSelectedItems,
    sharedId,
    shared,
    history,
    historySummary
  ]);

  return (
    <ProofMapperContext.Provider value={contextValue}>
      {children}
    </ProofMapperContext.Provider>
  );
};

// Hook
export const useProofMapper = (): ProofMapperContextType => {
  const context = useContext(ProofMapperContext);
  if (context === undefined) {
    throw new Error('useProofMapper must be used within a ProofMapperProvider');
  }
  return context;
};
